import axios from 'axios'
import { Toast } from 'mint-ui'
import vueCookie from 'vue-cookie'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 5000000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(config => {
  // Do something before request is sent
  if (vueCookie.get('netopstec_token') !== null) {
    config.headers['Authorization'] = 'Bearer ' + vueCookie.get('netopstec_token')
  }
  return config
}, error => {
  // Do something with request error
  console.log('error = ' + JSON.stringify(error)) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => response,
  error => {
    console.log('message = ' + error.response.data.message)
    console.log('msg = ' + error.response.data.msg)
    Toast({
      message: error.response.data.msg === null ? '系统错误' : error.response.data.msg,
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
